package zapx

import (
	"common/sentryx"
	"fmt"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"io"
	"os"
)

type LoggerStruct struct {
	*zap.Logger
	AppName *string
}

type LoggerStructOpt func(l *LoggerStruct) error

var Logger *LoggerStruct

// WithAppName 设置app名称
func WithAppName(appName string) LoggerStructOpt {
	return func(l *LoggerStruct) error {
		l.AppName = &appName
		return nil
	}
}

// WithSentryLogger 使用sentry作为日志收集器
func WithSentryLogger() LoggerStructOpt {
	return func(l *LoggerStruct) error {
		l.Logger = zap.New(
			zapcore.NewCore(
				zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()),
				zapcore.AddSync(io.MultiWriter(os.Stdout, sentryx.SentryX)),
				zapcore.DebugLevel,
			),
		)
		return nil
	}
}

// WithDefaultLogger 默认的日志记录
func WithDefaultLogger() LoggerStructOpt {
	return func(l *LoggerStruct) error {
		zlogger, err := zap.NewDevelopment()
		if err != nil {
			return err
		}
		l.Logger = zlogger
		return nil
	}
}

// Init 初始化日志
func Init(opts ...LoggerStructOpt) error {
	Logger = &LoggerStruct{
		nil, nil,
	}
	for _, opt := range opts {
		if err := opt(Logger); err != nil {
			panic(err)
		}
	}
	return nil
}

// Error 记录错误日志
func (l *LoggerStruct) Error(msg string, fields ...zap.Field) {
	if l.AppName != nil {
		msg = fmt.Sprintf("[%s],%s", *l.AppName, msg)
	}
	l.Logger.Error(msg, fields...)
}
